<template>
  <!-- 操作证表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="70%"
    draggable
    @close="closeDialog"
  >
    <el-descriptions
      class="margin-top"
      title=""
      :column="2"
      size="large"
      v-show="props.isReadonly"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">操作证编号</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.certificateCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">发证时间</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.issuanceTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">部门名称</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.departmentName }}
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">班组名称</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.teamName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">成员姓名</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.personName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备编码</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.assetCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备名称</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.assetName }}
        </div>
      </el-descriptions-item>

      <el-descriptions-item :span="3">
        <template #label>
          <div class="cell-item">图片</div>
        </template>
        <div v-if="formData.images && formData.images.length">
          <CommonUploadFile
            :showText="false"
            :isRead="props.isReadonly"
            :files="formData.images"
            @update-files="updateFormFiles"
          />
        </div>
        <div v-else>无</div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.remarks }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建时间</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createdUserId }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建人名</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createdUserName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">更新时间</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.lastUpdateTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">更新人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.lastUpdatedUserId }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">更新人名</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.lastUpdatedUserName }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="操作证编号"
            label-width="80px"
            style="white-space: nowrap"
          >
            <el-input
              v-model="formData.certificateCode"
              placeholder="请输入操作证编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="使用部门"
            prop="departmentName"
            label-width="80px"
          >
            <SelectOriganizationDangerGrant
              @change="(ids:string) => getSelectIds(ids, '使用部门')"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('部门')"
              :selectData="formData.departmentId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="班组" prop="teamId" label-width="80px">
            <el-select
              v-model="formData.teamId"
              placeholder="请选择班组"
              clearable
              @change="handleTeamChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in crewList"
                :key="`${item.id}`"
                :label="`${item.teamName}`"
                :value="`${item.id}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成员姓名" prop="personId" label-width="80px">
            <el-select
              v-model="formData.personId"
              placeholder="请选择成员"
              :disabled="!formData.teamId"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in memberList"
                :key="`${item.id}`"
                :label="`${item.memberName}`"
                :value="`${item.id}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备" prop="assetCode" label-width="80px">
            <el-select
              v-model="formData.assetCode"
              placeholder="请选择设备"
              clearable
              :disabled="!formData.usingDepartmentId"
              style="width: 100%"
            >
              <el-option
                v-for="item in deviceList"
                :key="`${item.assetCode}`"
                :label="`${item.assetName}`"
                :value="`${item.assetCode}`"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="上传图片">
          <CommonUploadFile
            :isRead="props.isReadonly"
            :files="formData.images"
            @update-files="updateFormFiles"
          />
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { getCrewListApi, getCrewMemberListApi } from "@/utils/commonData"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESEAMOPERATIONCERTIFICATEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  version: [],
  certificateCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  issuanceTime: [],
  departmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  departmentName: [
    { min: 1, max: 90, message: "长度在 1 到 90 个字符", trigger: "blur" },
  ],
  teamId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  teamName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  personId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  personName: [
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  assetId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

onMounted(() => {
  getCrews();
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  certificateCode: "",
  issuanceTime: "",
  departmentId: "",
  departmentName: "",
  teamId: "",
  teamName: "",
  personId: "",
  personName: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  images: [],

  // 维修信息
  repairTeamId: "",
  repairTeamCode: "",
  repairTeamName: "",
  repairTeamUser: "",
  repairTeamUserName: "",
  repairTeamUserEmpNo: "",
});

watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        certificateCode,
        issuanceTime,
        departmentId,
        departmentName,
        teamId,
        teamName,
        personId,
        personName,
        assetId,
        assetCode,
        assetName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        certificateCode,
        issuanceTime,
        departmentId,
        departmentName,
        teamId,
        teamName,
        personId,
        personName,
        assetId,
        assetCode,
        assetName,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      getCrews();
      memberList.value =
        (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.certificateCode = "";
  formData.issuanceTime = "";
  formData.departmentId = "";
  formData.departmentName = "";
  formData.teamId = "";
  formData.teamName = "";
  formData.personId = "";
  formData.personName = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 操作证表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eamoperationcertificate/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

function getSelectIds(ids: [] | string, item: string) {
  if (ids) {
    if (item == "使用部门") {
      formData.usingDepartmentId = ids;
      formData.departmentId = ids;
      getDevicesByDepartment(ids);
    } else if (item == "管理部门") {
      formData.manageDepartmentId = ids;
      personList.value = [];
      changeDept(ids, item);
    } else if (item == "维修部门") {
      formData.repairDepartmentId = ids;
      personList1.value = [];
      changeDept(ids, item);
    }
  } else {
    if (item == "使用部门") {
      formData.usingDepartmentId = "";
      formData.assetCode = "";
    } else if (item == "管理部门") {
      formData.manageDepartmentId = "";
      formData.assetManagerId = "";
      personList.value = [];
    } else if (item == "维修部门") {
      formData.repairDepartmentId = "";
      formData.repairManagerId = "";
      personList1.value = [];
    }
  }
}

// 获取维护班组列表
const crewList = ref(<any>[]);

async function getCrews() {
  crewList.value = (await getCrewListApi({ teamType: "1" })) || [];
}

const changeCrew = async (id: any) => {
  formData.repairTeamId = id;
  if (id) {
    crewList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamCode = item.teamCode;
        formData.repairTeamName = item.teamName;
      }
    });
  } else {
    formData.repairTeamCode = "";
    formData.repairTeamName = "";
  }
  formData.repairTeamUserName = "";
  formData.repairTeamUserEmpNo = "";
  formData.repairTeamUser = "";

  memberList.value =
    (await getCrewMemberListApi({ id: formData.repairTeamId })) || [];
};

//人员列表
const memberList = ref(<any>[]);
const handleTeamChange = async (teamId: any) => {
  // 清空已选人员
  formData.personId = "";
  if (teamId) {
    memberList.value =
      (await getCrewMemberListApi({ id: formData.teamId })) || [];
  } else {
    memberList.value = [];
  }
};

const deviceList = ref([]); // 设备列表

async function getDevicesByDepartment(id: string) {
  try {
    // 这里调用您的API，根据部门ID获取设备列表
    const { data } = await request({
      url: `/eam/eamoperationcertificate/queryEquipmentByDepartmentId/${id}`,
      method: "get",
    });
    deviceList.value = data;
  } catch (error) {
    console.error("获取设备列表失败:", error);
    ElMessage.error("获取设备列表失败");
  }
}

const dataObject = (item: string) => {
  return {
    name:
      item == "使用部门"
        ? "使用部门"
        : item == "管理部门"
        ? "管理部门"
        : "维修部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

const changeMember = (id: any) => {
  formData.repairTeamUser = id;
  if (id) {
    memberList.value.forEach((item: any) => {
      if (item.id === id) {
        formData.repairTeamUserEmpNo = item.memberEmpNo;
        formData.repairTeamUserName = item.memberName;
      }
    });
  } else {
    formData.repairTeamUserEmpNo = "";
    formData.repairTeamUserName = "";
  }
};

// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}
</script>
